<?php

namespace App\Http\Resources\CruiseCheck\Merchant;

use App\Http\Resources\BaseResource;
use App\Models\Cruise\CruiseCheckSelfTaskModel;
use App\Models\Cruise\CruiseOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class ShopSelfCheckDetailListResource extends BaseResource
{
    public static CruiseCheckSelfTaskModel $checkSelfTaskModel;
    public static int                      $executeStartSecond;
    public static int                      $executeEndSecond;

    public static array $userLists = [];

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function toArray($request): array
    {

        $submitUid  = attributeGet($this, "cruiseCheckDetailsRel.createdByUid", 0);
        $submitTime = "";
        if ($submitUid > 0) {
            $submitTime = date("Y-m-d H:i:s", $this->cruiseCheckDetailsRel->submitTime);
        }


        return [
            "id"                    => $this->id,
            'detailId'              => $this->cruiseCheckDetailsRel->id,
            "shopId"                => $this->id,
            "templateType"          => $this->templateType,
            "taskId"                => $this->taskId,
            "date"                  => $this->date,
            "status"                => $this->status,
            "cruiseOrderId"         => $this->cruiseOrderId,
            "executeStartTime"      => date("Y-m-d H:i:s",
                strtotime($this->createdAt->format("Y-m-d")) + self::$executeStartSecond),
            "executeEndTime"        => date("Y-m-d H:i:s",
                strtotime($this->createdAt->format("Y-m-d")) + self::$executeEndSecond),
            "cruiseOrderStatus"     => $this->cruiseOrderRel->status,
            "cruiseOrderStatusText" => $this->getStatusText(),
            "lastOperateTime"       => $submitTime,
            "lastOperateUsername"   => self::$userLists[$submitUid] ?? "",
        ];
    }

    /**
     * @return string
     * @throws \Exception
     */
    public function getStatusText(): string
    {
        switch ($this->cruiseOrderRel->status) {
            case CruiseOrderModel::STATUS_NOT_SUBMIT:
                list($startTimestamp, $endTimestamp) = CruiseCheckSelfTaskModel::getExecuteRuleCycle(
                    self::$checkSelfTaskModel,
                    $this->createdAt->timestamp
                );
                if (time() > $endTimestamp) {
                    return "已过期";
                }
                return CruiseOrderModel::CRUISE_STATUS_MAPPING[$this->cruiseOrderRel->status];
            case CruiseOrderModel::STATUS_NOT_REVIEW:
                return "已提交";
            default:
                return CruiseOrderModel::CRUISE_STATUS_MAPPING[$this->cruiseOrderRel->status] ?? "";
        }
    }
}
